'use strict';

const Service = require('egg').Service;
const ulid = require('../public/ulid');

class SnListService extends Service {
  async list(params) {
    const Op = this.ctx.model.Sequelize.Op;
    const where = {};
    where.tid = params.tid;
    if (params.search) {
      where.SN = { [Op.like]: '%' + params.search + '%' };
    }
    return await this.ctx.model.SnList.findAndCountAll({
      where,
      order: [[ 'createdAt', 'DESC' ]],
      offset: parseInt((params.page - 1) * params.limit),
      limit: parseInt(params.limit),
    });
  }
  async create(params) {
    await this.ctx.model.SnList.create({
      id: ulid.ulid(),
      SN: params.SN,
      tid: params.tid,
    });
  }
  async delete(params) {
    await this.ctx.model.SnList.destroy({ where: { id: params.id } });
  }
  async snverify(params) {
    const result = {
      msg: '',
      flag: false,
    };
    const snResult = await this.ctx.model.SnList.findOne({ where: { tid: params.tid, SN: params.SN } });
    if (!snResult) {
      // 不存在
      result.msg = 'successful';
      result.flag = true;
      return result;
    }
    // 存在
    result.msg = 'The SN is already exists.';
    result.flag = false;
    return result;

  }
  async tr069List(params) {
    const tid = params.tid;
    // const where = {
    //   acsSupport: true,
    // };
    console.log('123123123')
    const where = {};
    where.tid = tid;
    if (params.search) {
      if(params.search.indexOf(',') >0){
        let snList = params.search.split(',');
        where.sn = {
          $in : snList
        }
      }else{
        where.$or= [{sn:new RegExp(params.search,"i")},{ONUname:new RegExp(params.search,"i")}]
      }
    }
    if (params.group) {
      where.onugroupId = params.group;
    }
    if(params.oltId != "Any"){
      where.oltId = params.oltId
    }  
    if(params.ponCard){
      where.slot =   parseInt(params.ponCard)  
    }  
    if(params.status != "All"){
      where.status = params.status
    }
    
   if(params.ponPort ){
    where.port =parseInt(params.ponPort) 
   }
    const result = {
      count: '',
      rows: '',
    };
     console.log(where)
    result.count = await this.ctx.model.OnuList.find(where).count('_id');
    result.rows = await this.ctx.model.OnuList.aggregate([
      {
        $match: where,  
      },
      {
        $lookup: { // 左连接
          from: 'olt', // 关联到olt表
          localField: 'oltId', // oltType 表关联的字段
          foreignField: '_id', // script 表关联的字段
          as: 'olt',
        },
      },
    ]).sort({ oltId: 1, slot: 1, port: 1, number: 1 }).skip(parseInt((params.page - 1) * params.limit))
      .limit(parseInt(params.limit));
     
    return result;  
  }
}

module.exports = SnListService;
